package com.ebo.httpcall4j.core.autoconfig;


import com.ebo.httpcall4j.core.ApplicationContextHolder;
import com.ebo.httpcall4j.core.HttpCallService;
import com.ebo.httpcall4j.core.HttpCallServiceImpl;
import com.ebo.httpcall4j.core.log.HttpCallLogService;
import com.ebo.httpcall4j.core.repository.HttpCallLogRepository;
import com.ebo.httpcall4j.core.repository.JdbcHttpCallLogRepository;
import com.ebo.httpcall4j.core.rerun.HttpCallRerunService;
import com.ebo.httpcall4j.core.retry.RetryInterceptor;
import com.ebo.httpcall4j.core.retry.RetryStrategy;
import okhttp3.OkHttpClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.concurrent.TimeUnit;

@Configuration
@Import({ApplicationContextHolder.class})
public class HttpCallAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public HttpCallService httpCallService(OkHttpClient okHttpClient, HttpCallLogService httpCallLogService) {
        return new HttpCallServiceImpl(okHttpClient, httpCallLogService, ApplicationContextHolder.getContext());
    }

    @Bean
    @ConditionalOnMissingBean
    public OkHttpClient okHttpClient() {
        return new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(new RetryInterceptor(RetryStrategy.defaultStrategy()))
                .build();
    }

    @Bean
    @ConditionalOnMissingBean
    public HttpCallLogService httpCallLogService(HttpCallLogRepository httpCallLogRepository) {
        return new HttpCallLogService(httpCallLogRepository);
    }

    @Bean
    @ConditionalOnMissingBean
    public HttpCallLogRepository httpCallLogRepository(JdbcTemplate jdbcTemplate) {
        return new JdbcHttpCallLogRepository(jdbcTemplate);
    }

    @Bean
    @ConditionalOnMissingBean
    public HttpCallRerunService httpCallRerunService(HttpCallLogRepository logRepository, HttpCallService httpCallService, HttpCallLogService logService) {
        return new HttpCallRerunService(logRepository, httpCallService, logService);
    }

}